package com.army.study.component.listcomponent;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;

import java.util.List;

public abstract class ListComponentAdapter<T> extends BaseItemProvider {
    // 上下文
    private final Context context;
    // 泛型列表
    private final List<T> lists;
    // xml布局Id
    private final int xmlId;

    /**
     * 构造方法
     * @param context
     * @param lists
     * @param xmlId
     */
    protected ListComponentAdapter(Context context, List<T> lists, int xmlId) {
        this.context = context;
        this.lists = lists;
        this.xmlId = xmlId;
    }

    // 绑定视图持有者
    public abstract void onBindViewHolder(CommentViewHolder commentViewHolder, T item, int position);

    /**
     * 获取列表组件项数量
     * @return
     */
    @Override
    public int getCount() {
        return lists.size();
    }

    /**
     * 获取指定下标的列表项
     * @param i
     * @return
     */
    @Override
    public T getItem(int i) {
        return lists.get(i);
    }

    /**
     * 获取列表下标
     * @param i
     * @return
     */
    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * 获取组件
     * @param i
     * @param component
     * @param componentContainer
     * @return
     */
    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        // 根据构造方法传过来的xmlId, 获取组件
        CommentViewHolder commentViewHolder = CommentViewHolder.getCommentViewHolder(context, component, xmlId);
        // 根据构造方法传过来的lists, 获取指定的视图
        T view = lists.get(i);
        // 绑定抽象视图持有者, 实现类处理逻辑
        onBindViewHolder(commentViewHolder, view, i);
        // 设置列表项点击事件
        commentViewHolder.convertView.setClickedListener(component1 -> onItemClick(component, view, i));
        // 返回转换视图
        return commentViewHolder.convertView;
    }

    /**
     * 列表项单击
     * @param component
     * @param item
     * @param position
     */
    public void onItemClick(Component component, T item, int position) {}
}
